package com.promise.jokerdream.work.use

import com.promise.jokerdream.config.game.BagGoodsUseGameConfig
import com.promise.jokerdream.config.game.BagGoodsUseType
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.model.bag.BagGoods
import com.promise.jokerdream.model.bag.BagGoodsMapping
import com.promise.jokerdream.model.bag.BagGoodsStorageType
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 背包工作
class BagGoodsUseWork(
    private val config: BagGoodsUseGameConfig,
    uin: String
): BaseWork(uin) {
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }
    
    override val name: String
        get() = "背包"
    
    override suspend fun executeWork(): WorkResult {
        return try {
            when (config.useType) {
                BagGoodsUseType.STRATEGY -> executeStrategyWork()
                BagGoodsUseType.POTION -> executePotionWork()
            }
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }
    
    /**
     * 执行锦囊工作
     */
    private suspend fun executeStrategyWork(): WorkResult {
        
        // 1. 查询所有物品
        val queryResult = gameApi.queryBagGoods(uin)
        return queryResult.foldWithApiException(
            onSuccess = { response ->
                val bagGoods = response.bag
                
                // 2. 过滤storage为STRATEGY的物品
                val strategyItems = bagGoods.filter { it.storage == BagGoodsStorageType.STRATEGY.value }
                
                // 3. 查找宝箱物品
                val treasureChestItems = bagGoods.filter { bagGoods ->
                    BagGoodsMapping.treasureChestList.contains(bagGoods.id.toString())
                }
                
                // 4. 准备需要使用的物品（包含数量信息），去重
                val itemsToUse = (strategyItems + treasureChestItems).distinctBy { it.id }
                
                // 5. 根据数量循环使用物品
                useBagGoods(itemsToUse)
            },
            onFailure = { code, msg ->
                historyManager.addHistory(name, msg, code)
                WorkResult.Failure(Exception("查询背包物品失败"), msg)
            }
        )
    }
    
    /**
     * 执行吃药工作（暂不实现）
     */
    private suspend fun executePotionWork(): WorkResult {
        return WorkResult.Success
    }
    
    /**
     * 使用物品列表
     */
    private suspend fun useBagGoods(bagGoodsList: List<BagGoods>): WorkResult {
        for (bagGoods in bagGoodsList) {
            val itemId = bagGoods.id.toString()

            // 根据数量循环使用物品
            repeat(bagGoods.num) {
                val useResult = gameApi.useGoods(uin, itemId)
                useResult.foldWithApiException(
                    onSuccess = { response ->
                        historyManager.addHistory(name, response.getDescription())
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, msg, code)
                    }
                )
            }
        }
        
        return WorkResult.Success
    }
}